#引入相关模块
import network,time,dht,json
from machine import I2C,Pin,Timer
from ssd1306 import SSD1306_I2C

WIFI_LED=Pin(2, Pin.OUT) #初始化WIFI指示灯
wlan = network.WLAN(network.STA_IF) #STA模式

#初始化相关模块
i2c = I2C(sda=Pin(13), scl=Pin(14))
oled = SSD1306_I2C(128, 64, i2c, addr=0x3c)

#创建DTH11对象
d = dht.DHT11(Pin(27)) #传感器连接到引脚15
time.sleep(1)   #首次启动停顿1秒让传感器稳定

#OLED屏幕显示，没有屏幕可以把这个注释掉
def Oled_show():   
    d.measure()         #温湿度采集
    oled.fill(0) #清屏背景黑色
    oled.text('tem: '+str(d.temperature() )+' C',0,38)   #温度显示
    oled.text('hum: '+str(d.humidity())+' %',0,48)  #湿度显示
    oled.show()   

#WIFI连接函数
def WIFI_Connect():
    wlan.active(True)                   #激活接口
    start_time=time.time()              #记录时间做超时判断

    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect('123', '12345678') #输入WIFI账号密码

        while not wlan.isconnected():

            #LED闪烁提示
            WIFI_LED.value(1)
            time.sleep_ms(300)
            WIFI_LED.value(0)
            time.sleep_ms(300)

            #超时判断,15秒没连接成功判定为超时
            if time.time()-start_time > 15 :
                print('WIFI Connected Timeout!')
                break

    if wlan.isconnected():
        #串口打印信息
        print('network information:', wlan.ifconfig())
        return True
    else:
        return False

def MQTT_Send(tim):
    Oled_show()     #OLED屏幕显示
    mymessage = {"id":"123", "version":"1.0",
                 "params":{"Temp":{"value":d.temperature()},      #温度
                 "humidity":{"value":d.humidity()}}}              #湿度
#     print(mymessage)                                            #用于测试数据是否接收正常
    msg_json = json.dumps(mymessage)
    client.publish(topic=publish_Topic, msg=msg_json)
    client.check_msg()
                 
def MQTT_callback(topic, msg):
    #post/reply主题上报数据，如果返回success代表上报云平台成功
    print("topic:{}".format(topic))
    print("msg:{}".format(msg))

if WIFI_Connect():
    #订阅主题
    publish_Topic='$sys/4QBhkhln6H/DeviceLZY27240926/thing/property/post'
    post_Topic='$sys/4QBhkhln6H/DeviceLZY27240926/thing/property/post/reply'
    # 客户端ID
    CLIENT_ID = 'DeviceLZY27240926'
    # user_name名称
    user_name = '4QBhkhln6H'
    user_password = 'version=2018-10-31&res=products%2F4QBhkhln6H%2Fdevices%2FDeviceLZY27240926&et=1800000000&method=md5&sign=Mw6yI2B92Ufo1YW3bRLP8Q%3D%3D'
    SERVER = 'mqtts.heclouds.com'
    PORT = 1883
    client = MQTTClient(CLIENT_ID, SERVER, 0, user_name, user_password, 60)
    print('start connect!')#开始连接云平台
    client.set_callback(MQTT_callback)
    client.connect()
    print('success connect!')#连接成功
    client.subscribe(post_Topic)
#     client.subscribe(subscribe_Topic)
#开启RTOS定时器，编号为-1
tim = Timer(-1)
tim.init(period=2000, mode=Timer.PERIODIC,callback=MQTT_Send) #周期为2000ms

